import { defineStore } from 'pinia'
import { getRouters } from '@/api/login'
import { routes } from '@/router/routes'
export const useMenuStore = defineStore('menuId', {
    state: () => {
        return {
            menuList: [],
            mapMenuList: null
        }
    },
    actions: {
        async getMenu(rolePerm) {
            const res = await getRouters(rolePerm)
            const menu = normalizeMenu(res.data);
            this.menuList = menu.routers;
            this.mapMenuList = menu.authMenuMap;
            // console.log(this.menuList);
        },
    },
    persist: {
        enabled: true,
        strategies: [{
            storage: localStorage,
        }]
    },
})
//生成map扁平化格式，方便判断（如果当前用户没有某一个权限那么就不能进入某一个路由中）
function normalizeMenu(routers) {
    const authMap = new Map();
    let router = [
        ...routes,
        ...routers
    ]
    const authMenuMap = normalizeMenuItem(router, authMap);
    return {
        routers,
        authMenuMap
    }
}
function normalizeMenuItem(routers, map) {
    routers.forEach(item => {
        map.set(item.path, item);
        if (item.children) {
            return normalizeMenuItem(item.children, map);
        }
    })
    return map;
}